<?php
/**
 * Date: 10/27/12
 * Time: 2:00 PM
 * User: Amitav Roy
 */
class Dashboard_m extends CI_Model {
	function __construct() {
		parent::__construct();
	}

	/**
	 * This function will return the last ten transactions which is used to show
	 * the latest transactions on the home page. I have changed the count on this
	 * later to 5 transactions, for design purpose.
	 */
	function last_ten_transaction() {
		$this->load->model('transactions/transaction_m','trans_model');
		$this->trans_model->base_view_expense_getter();

		// Adding the limit
		$this->db->limit(5);

		// Ordering with default points.
		$this->db->order_by('e.date','DESC');
		$this->db->order_by('e.eid','DESC');

		// Firing the query
		$query = $this->db->get();

		return $query->result();
	}

	/**
	 * This function checked the category wise expenditure for this month and
	 * returns the json array which is then used by Google Graphs.
	 * @return json string
	 */
	function category_trend() {
		$date_min = date('Y-m-01',time());

		$this->db->select_sum('amount');
		$this->db->select('name');
		$this->db->from('view_expense_list');
		$this->db->where('date >= ', $date_min);
		$this->db->group_by('name');
		$this->db->order_by('amount','DESC');
		$this->db->limit(5);
		$query = $this->db->get();

		// return $this->db->last_query();
		$result = $query->result();
		$data = array();

		// Formatting the data for Google Chart format. Array inside object.
		foreach ($result as $k=>$v) {
			$data[$k] = array($v->name,intval($v->amount));
		}

		return json_encode($data);
	}
	

	/**
	 * Function to get the data of the bill payment made on the current month.
	 */
	function bills_payments_this_month() {
		$date_min = date('Y-m-01',time());
		$query_string = "SELECT br.name, b.amount, b.date 
				FROM bills b 
				LEFT JOIN description d ON b.bid = d.eid AND d.entity_type = 'bills' 
				LEFT JOIN bills_billers bb ON bb.bid = b.bid 
				LEFT JOIN billers br ON br.brid = bb.brid 
				WHERE b.date >= ?
				ORDER BY b.date DESC";
		$query = $this->db->query($query_string, array($date_min));
		
		return $query->result();
	}
}
